class BinaryTree:
  """list based binary tree
  """
  def __init__(self, data, left = None, right = None):
    self.head = [data, left, right]
    self.data = data
    
  def is_empty(self):
    if self.head is None:
      return True
    return False

  def root(self):
    if not self.is_empty():
      return self.head[0]

  def left(self):
    if self.head is not None:
      return self.head[1]
    
  def right(self):
    if self.head is not None:
      return self.head[2]
  
  def set_root(self, root):
    if self.head is None:
      raise ValueError("empty tree cant set root!")
    self.head[0] = root

  def preorder(self):
    """先根遍历
    """
    result = []
    left = []
    right = []
    if self.head is None:
        return result
    else:
        result.append(self.head[0])         # 先访问根节点
        if self.head[1] is not None:
            left = self.head[1].preorder() # 遍历左子树
        if self.head[2] is not None:
            right = self.head[2].preorder() # 遍历右子树
        return result + left + right
        
